package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.JPushEnum;
import com.lst.common.JPushMessage;
import com.lst.entity.request.AnswerReqPara;
import com.lst.model.Answer;
import com.lst.model.MstClient;
import com.lst.model.MstMessage;
import com.lst.model.Question;
import com.lst.service.AnswerService;
import com.lst.service.MstClientService;
import com.lst.service.MstMessageService;
import com.lst.service.QuestionService;
import com.lst.utils.RequestUtils;
import com.lst.utils.SensitiveUtil;


/**
 * @ClassName: AnswerAddServlet
 * @Description: 回答添加接口
 * 
 */
public class AnswerAddServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private AnswerService answerService = ctx.getBean(AnswerService.class);
	
	private QuestionService questionService = ctx.getBean(QuestionService.class);
	
	private MstClientService mstClientService = ctx.getBean(MstClientService.class);
	
	private MstMessageService mstMessageService = ctx.getBean(MstMessageService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		BaseResponse resPara = new BaseResponse();

		try {
			AnswerReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			int userid = Integer.parseInt(reqPara.getUserid());
			int answerSourceId = Integer.parseInt(reqPara.getAnswerSourceId());	
			
			int friendId = 0;
			
			String answerTitle = reqPara.getAnswerTitle();
			String answerDetail = reqPara.getAnswerDetail();

//			String str1=SensitiveUtil.check(answerTitle);
//			String str2=SensitiveUtil.check(answerDetail);
//		    if((str1.length()==2&&str2.length()==2) || (str1==""&&str2=="")){
		    	//查询是否回答过问题
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("answerSourceId", answerSourceId);
				map.put("answerCreateUser", userid);
				Answer answer=answerService.selectByMap(map);
				
				//回答过修改，未回答过,创建
				if(answer!=null){
					answer.setAnswerDetail(answerDetail);
					answer.setAnswerTitle(answerTitle);
					answer.setAnswerCreateDate(startDate);
					answerService.updateAnswer(answer);
				}else{
					Answer md = new Answer();
					
					md.setAnswerCreateUser(userid);
			        md.setAnswerSourceId(answerSourceId);
			        md.setAnswerTitle(answerTitle);
			        md.setAnswerDetail(answerDetail);
					md.setAnswerCreateDate(startDate);
					md.setIsDelete(false);
					
					answerService.insert(md);
					
					Question question=questionService.selectByPrimaryKey(answerSourceId);
					int answerNum=question.getAnswerNum();
					question.setAnswerNum(answerNum+1);
					questionService.updateQuestion(question);
					
					friendId=question.getCreateUser();
					//回答发通知
					if(userid!=friendId){
							MstClient mstClient = mstClientService.selectByPrimaryKey(userid);
							if (mstClient != null) {
								String name = mstClient.getNickname();

								MstMessage message = new MstMessage();
								message.setReceiveid(friendId);
								message.setReceivetype(CommCode.SYSCODE_MSG_TYPE_RECEIVE_CLIENT);
								message.setSendid(userid);
								message.setSendtype(CommCode.SYSCODE_MSG_TYPE_SEND_CLIENT);
								message.setEnabled(true);
								message.setIsdeleted(false);
								message.setCreateuser(-1);
								message.setCreatedate(startDate);
								message.setReserved1(answerSourceId);
							    message.setContent("回答了你的问题！");
								message.setReserved2(CommCode.SYSTEM_CARESEL_RANGE_QUESTION);
								message.setReserved7(false);
								message.setType(CommCode.SYSCODE_MSG_TYPE_PUSH);
								mstMessageService.insert(message);
								message.setReserved12(name);
								JPushMessage.pushMessage(message, JPushEnum.ALL_ALIAS);
							}
					}
					
				}
		    	resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
//		    }else{
//				resPara.setCode(CommCode.M_A000000);
//				resPara.setMessage("含有违禁词，请修改");
//		    }
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
		//	logger.info("AnswerAddServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

		//	logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public AnswerReqPara getReqPara(HttpServletRequest request) {

		AnswerReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new AnswerReqPara());

			reqPara = (AnswerReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String answerSourceId = request.getParameter("answerSourceId");
			String answerTitle = request.getParameter("answerTitle");
			String answerDetail = request.getParameter("answerDetail");
	
			
//			logger.info("reqPara userid:" + userid);
//			logger.info("reqPara answerSourceId: " + answerSourceId);
//			logger.info("reqPara answerTitle: " + answerTitle);
//			logger.info("reqPara answerDetail:" + answerDetail);
			

	        reqPara.setAnswerSourceId(answerSourceId);
	        reqPara.setAnswerTitle(answerTitle);
	        reqPara.setAnswerDetail(answerDetail);
	        reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		AnswerReqPara cdReqPara = (AnswerReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getAnswerSourceId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("回答目标问题id为空");
		} else if (StringUtils.isEmpty(cdReqPara.getAnswerDetail())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("回答详情为空");
		}else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else {
			flag = true;
		}

		return  flag;
	}

}
